﻿@page "/Tracks"
@using Jx.Toolbox.Extensions
@using JxAudio.Front.Data
@using JxAudio.Front.Filter
@using JxAudio.TransVo
@using Microsoft.Extensions.Localization

@inject HttpClient Http
@inject IDispatchService<AddTrackMessage> DispatchService
@inject IStringLocalizer<Tracks> StringLocalizer

<PageTitle>@StringLocalizer["Title"] - JxAudio</PageTitle>

<div style="height: calc(100vh - 5.1rem - 82px)">
    <FrontTable TItem="TrackVo" ShowToolbar="true" ShowDefaultButtons="false" ShowExtendButtons="true" 
                IsMultipleSelect="true" SelectedRows="SelectedRows"
                ShowExtendDeleteButton="false" ShowExtendEditButton="false" OnQueryAsync="OnQueryAsync">
        <TableToolbarTemplate>
            <TableToolbarButton TItem="TrackVo" Text="@StringLocalizer["PlaySelected"]" Icon="fa fa-play" 
                                OnClick="() => PlayList(SelectedRows, PlayType.Replace)"></TableToolbarButton>
            <TableToolbarButton TItem="TrackVo" Text="@StringLocalizer["AddSelected"]" Icon="fa fa-plus"
                                OnClick="() => PlayList(SelectedRows, PlayType.AddAndPlay)"></TableToolbarButton>
        </TableToolbarTemplate>
        <TableColumns>
            <TableColumn @bind-Field="@context.Title" Searchable="true" Filterable="true" Sortable="true">
                <Template Context="value">
                    @if (value.Value.IsNullOrEmpty())
                    {
                        @value.Row.Name
                    }
                    else
                    {
                        @value.Value
                    }
                </Template>
            </TableColumn>
            <TableColumn @bind-Field="@context.Artists" >
                <Template Context="value">
                    @if (value.Value is { Count: > 0 })
                    {
                        @foreach (var artist in value.Value)
                        {
                            <LinkButton Url="@($"/Artist/{artist.Id}")">@artist.Name</LinkButton>
                            @:&nbsp;
                        }
                    }
                    else
                    {
                        @:未知歌手
                    }
                </Template>
            </TableColumn>
            <TableColumn @bind-Field="@context.Album" Filterable="true" Searchable="true" Sortable="true" CustomSearch="SearchAlbum">
                <FilterTemplate>
                    <ArtistFilter></ArtistFilter>
                </FilterTemplate>
                <Template Context="value">
                    @if (value.Value != null)
                    {
                        <LinkButton Url="@($"/Album/{value.Value.Id}")">@value.Value.Title</LinkButton>
                    }
                    else
                    {
                        @:未知专辑
                    }
                </Template>
            </TableColumn>
            <TableColumn @bind-Field="@context.Name" Text="音频格式">
                <Template Context="value">
                    @Path.GetExtension(value.Value!)[1..].ToUpper()
                </Template>
            </TableColumn>
            <TableColumn @bind-Field="@context.BitRate"></TableColumn>
            <TableColumn @bind-Field="@context.Size">
                <Template Context="value">
                    @value.Value.ToSizeString()
                </Template>
            </TableColumn>
            <TableColumn @bind-Field="@context.Duration">
                <Template Context="value">
                    @value.Value.ToTimeString()
                </Template>
            </TableColumn>
        </TableColumns>
        <RowButtonTemplate>
            <TableCellButton Icon="fa fa-play" OnClick="@(() => Play(context, PlayType.Replace))"></TableCellButton>
            <TableCellButton Icon="fa fa-plus" OnClick="@(() => Play(context, PlayType.Add))"></TableCellButton>
            <TableCellButton Icon="@(context.Star? "fas fa-heart" : "far fa-heart")"
                             OnClick="() => Star(context)" style="color: red"></TableCellButton>
        </RowButtonTemplate>
    </FrontTable>
</div>

@code {

    public List<TrackVo> SelectedRows { get; set; } = [];
    
    private void PlayList(List<TrackVo> trackVos, PlayType type)
    {
        if (trackVos.Count == 0)
        {
            return;
        }
        DispatchService.Dispatch(new DispatchEntry<AddTrackMessage>()
        {
            Entry = new AddTrackMessage()
            {
                Tracks = trackVos,
                Type = type
            }
        });
    }

    private void Play(TrackVo track, PlayType type)
    {
        PlayList([track], type);
    }

    private async Task<QueryData<TrackVo>> OnQueryAsync(QueryPageOptions queryPageOptions)
    {
        QueryOptionsVo queryOptionsVo = new QueryOptionsVo
        {
            SortName = queryPageOptions.SortName.ToFieldName(),
            DynamicFilterInfo = queryPageOptions.ToDynamicFilter(),
            SortOrder = (int)queryPageOptions.SortOrder,
            IsPage = queryPageOptions.IsPage,
            PageIndex = queryPageOptions.PageIndex,
            PageItems = queryPageOptions.PageItems
        };
        var responseMessage = await Http.PostAsJsonAsync("/api/Track", queryOptionsVo);
        var vo = await responseMessage.Content.ReadFromJsonAsync<QueryData<TrackVo>>();
        if (vo == null)
        {
            return new QueryData<TrackVo>();
        }

        return vo;
    }

    private SearchFilterAction SearchAlbum(ITableColumn tableColumn, string? value)
    {
        return new SearchFilterAction(tableColumn.GetFieldName(), value);
    }
    
    private async Task Star(TrackVo trackVo)
    {
        if (trackVo.Star)
        {
            if (await Http.GetStringAsync("/api/Track/UnStar?id=" + trackVo.Id) == "s")
            {
                trackVo.Star = false;
            }
        }
        else
        {
            if (await Http.GetStringAsync("/api/Track/Star?id=" + trackVo.Id) == "s")
            {
                trackVo.Star = true;
            }
        }
    }

}